package cn.flying.cloud.flow.service.impl;

import javax.annotation.Resource;

import java.io.Serializable;
import java.util.List;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.flying.cloud.base.common.utils.Ft;
import cn.flying.cloud.base.common.vo.PageRequest;
import cn.flying.cloud.base.common.vo.PageResponse;
import cn.flying.cloud.flow.bo.FwProcAttributeBo;
import cn.flying.cloud.flow.bo.FwProcFormBo;
import cn.flying.cloud.flow.bo.FwProcInfoBo;
import cn.flying.cloud.flow.bo.FwTaskCandidateBo;
import cn.flying.cloud.flow.entity.FwProcAttribute;
import cn.flying.cloud.flow.entity.FwProcForm;
import cn.flying.cloud.flow.entity.FwProcInfo;
import cn.flying.cloud.flow.entity.FwProcNode;
import cn.flying.cloud.flow.entity.FwTaskCandidate;
import cn.flying.cloud.flow.mapper.FwProcInfoMapper;
import cn.flying.cloud.flow.service.FwProcAttributeService;
import cn.flying.cloud.flow.service.FwProcFormService;
import cn.flying.cloud.flow.service.FwProcInfoService;
import cn.flying.cloud.flow.service.FwProcNodeService;
import cn.flying.cloud.flow.service.FwTaskCandidateService;

/**
 * 流程定义信息表 服务实现类
 *
 * @author admin
 * @since 2024-10-28 20:09:38
 */
@Service
public class FwProcInfoServiceImpl extends ServiceImpl<FwProcInfoMapper, FwProcInfo> implements FwProcInfoService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private FwProcNodeService fwProcNodeService;
    @Resource
    private FwProcFormService fwProcFormService;
    @Resource
    private FwProcAttributeService fwProcAttributeService;
    @Resource
    private FwTaskCandidateService fwTaskCandidateService;

    /**
     * 查询总数
     *
     * @param param
     * @return
     */
    @Override
    public long countObj(FwProcInfoBo param) {
        return this.count(getLambdaQueryWrapper(param));
    }

    /**
     * 分页查询流程定义信息表数据
     *
     * @param request
     * @return
     */
    @Override
    public PageResponse<FwProcInfoBo> getPageList(PageRequest<FwProcInfoBo> request) {
        FwProcInfoBo param = request.getParam();
        LambdaQueryWrapper<FwProcInfo> wrapper = getLambdaQueryWrapper(param);
        wrapper.orderByDesc(FwProcInfo::getCreatedTime);
        Page<FwProcInfo> page = this.page(new Page<>(request.getPageNum(), request.getPageSize()), wrapper);
        return new PageResponse<>(page.getTotal(), (int) page.getCurrent(), page.getRecords().stream().map(FwProcInfo::toBO).collect(Collectors.toList()));
    }

    /**
     * 构建查询对象
     *
     * @param param
     * @return
     */
    private LambdaQueryWrapper<FwProcInfo> getLambdaQueryWrapper(FwProcInfoBo param) {
        LambdaQueryWrapper<FwProcInfo> wrapper = new LambdaQueryWrapper<>();
        // wrapper TODO
        return wrapper;
    }

    /**
     * 列表查询流程定义信息表数据
     *
     * @param param
     * @return
     */
    @Override
    public List<FwProcInfoBo> getList(FwProcInfoBo param) {
        LambdaQueryWrapper<FwProcInfo> wrapper = getLambdaQueryWrapper(param);
        // wrapper TODO
        List<FwProcInfo> list = this.list(wrapper);
        return list.stream().map(FwProcInfo::toBO).collect(Collectors.toList());
    }

    /**
     * 查询流程定义信息表详情数据
     *
     * @param param
     * @return
     */
    @Override
    public FwProcInfoBo getOneObj(FwProcInfoBo param) {
        LambdaQueryWrapper<FwProcInfo> wrapper = getLambdaQueryWrapper(param);
        if (wrapper.isEmptyOfWhere()) {
            return new FwProcInfoBo();
        }
        return this.getOne(wrapper).toBO();
    }

    /**
     * 根据Id查询流程定义信息表详情数据
     *
     * @param id
     * @return
     */
    @Override
    public FwProcInfoBo getObjById(Serializable id) {
        return this.getById(id).toBO();
    }

    /**
     * 新增流程定义信息表数据
     *
     * @param param
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean createObj(FwProcInfoBo param) {
        param.setTenantId(Ft.Local.TenantId());
        FwProcInfo obj = new FwProcInfo();
        obj.fromBO(param);
        return this.save(obj);
    }

    /**
     * 更新流程定义信息表数据
     *
     * @param param
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateObj(FwProcInfoBo param) {
        FwProcInfo obj = new FwProcInfo();
        obj.fromBO(param);
        return this.saveOrUpdate(obj);
    }

    /**
     * 删除流程定义信息表数据
     *
     * @param param
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteObj(FwProcInfoBo param) {
        LambdaQueryWrapper<FwProcInfo> wrapper = getLambdaQueryWrapper(param);
        // wrapper TODO
        return this.remove(wrapper);
    }

    /**
     * 根据Id删除流程定义信息表数据
     *
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteById(Serializable id) {
        return this.removeById(id);
    }

    /**
     * 拷贝流程定义相关配置从上一个版本获取
     *
     * @param procDefId
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void copy(String procDefId) {
        String[] keys = procDefId.split(":");
        LambdaQueryWrapper<FwProcInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FwProcInfo::getProcDefKey, keys[0]);
        wrapper.lt(FwProcInfo::getVersion, Integer.valueOf(keys[1]));
        wrapper.orderByDesc(FwProcInfo::getVersion);
        List<FwProcInfo> list = this.list(wrapper);
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        FwProcInfo procInfo = list.get(0);

        // 根据流程定义Id查询最新定义的节点
        List<String> nodeIds = fwProcNodeService.list(new LambdaQueryWrapper<FwProcNode>().eq(FwProcNode::getProcDefId, procDefId))
                .stream().map(FwProcNode::getNodeId).collect(Collectors.toList());

        // 将原来的复制到新的上
        List<FwProcForm> forms = fwProcFormService.list(new LambdaQueryWrapper<FwProcForm>().eq(FwProcForm::getProcDefId, procDefId));
        if (CollectionUtils.isEmpty(forms)) {
            FwProcFormBo form = new FwProcFormBo();
            form.setProcDefId(procInfo.getProcDefId());
            List<FwProcFormBo> formsOld = fwProcFormService.getList(form);
            List<FwProcForm> formsNew = formsOld.stream().filter(n -> nodeIds.contains(n.getNodeId())).map(n -> {
                FwProcForm temp = new FwProcForm();
                temp.setProcDefId(procDefId);
                temp.setProcDefKey(n.getProcDefKey());
                temp.setProcDefName(n.getProcDefName());
                temp.setNodeId(n.getNodeId());
                temp.setNodeName(n.getNodeName());
                temp.setFormKey(n.getFormKey());
                temp.setRouteTitle(n.getRouteTitle());
                temp.setRoutePath(n.getRoutePath());
                temp.setComponent(n.getComponent());
                temp.setFormBtn(n.getFormBtn());
                temp.setRemark(n.getRemark());
                temp.setTenantId(n.getTenantId());

                return temp;
            }).collect(Collectors.toList());

            fwProcFormService.saveBatch(formsNew);
        }
        List<FwProcAttribute> attributes = fwProcAttributeService.list(new LambdaQueryWrapper<FwProcAttribute>().eq(FwProcAttribute::getProcDefId, procDefId));
        if (CollectionUtils.isEmpty(attributes)) {
            FwProcAttributeBo attribute = new FwProcAttributeBo();
            attribute.setProcDefId(procInfo.getProcDefId());
            List<FwProcAttributeBo> attributesOld = fwProcAttributeService.getList(attribute);
            List<FwProcAttribute> attributesNew = attributesOld.stream().filter(n -> nodeIds.contains(n.getNodeId())).map(n -> {
                FwProcAttribute temp = new FwProcAttribute();
                temp.setEventType(n.getEventType());
                temp.setNodeName(n.getNodeName());
                temp.setNodeId(n.getNodeId());
                temp.setCallbackUrl(n.getCallbackUrl());
                temp.setAttrName(n.getAttrName());
                temp.setAttrValue(n.getAttrValue());
                temp.setProcDefId(procDefId);
                temp.setProcDefKey(n.getProcDefKey());
                temp.setRemark(n.getRemark());
                temp.setExt1(n.getExt1());
                temp.setExt2(n.getExt2());
                temp.setExt3(n.getExt3());
                temp.setTenantId(n.getTenantId());

                return temp;
            }).collect(Collectors.toList());

            fwProcAttributeService.saveBatch(attributesNew);
        }

        List<FwTaskCandidate> candidates = fwTaskCandidateService.list(new LambdaQueryWrapper<FwTaskCandidate>().eq(FwTaskCandidate::getProcDefId, procDefId));
        if (CollectionUtils.isEmpty(candidates)) {
            FwTaskCandidateBo candidate = new FwTaskCandidateBo();
            candidate.setProcDefId(procInfo.getProcDefId());
            List<FwTaskCandidateBo> candidatesOld = fwTaskCandidateService.getList(candidate);
            List<FwTaskCandidate> candidatesNew = candidatesOld.stream().filter(n -> nodeIds.contains(n.getNodeId())).map(n -> {
                FwTaskCandidate temp = new FwTaskCandidate();
                temp.setNodeId(n.getNodeId());
                temp.setNodeName(n.getNodeName());
                temp.setNodeType(n.getNodeType());
                temp.setCandidateUser(n.getCandidateUser());
                temp.setCandidatePost(n.getCandidatePost());
                temp.setCandidateRole(n.getCandidateRole());
                temp.setProcDefId(procDefId);
                temp.setProcDefKey(n.getProcDefKey());
                temp.setTenantId(n.getTenantId());

                return temp;
            }).collect(Collectors.toList());

            fwTaskCandidateService.saveBatch(candidatesNew);
        }
    }
}
